<template>
  <el-dialog :title="titleText" :visible.sync="showDialog" top="0" :close-on-click-modal="false" width="90%" @close="cancel">
    <el-form ref="form" :model="formData" class="el-form">
      <el-form-item :label="productionInventoryNoLabel" class="w50p" :rules="[{ required: true }]">
        <el-input v-model="formData.productionInventoryNo" clearable disabled />
      </el-form-item>
      <el-form-item label="创建时间：" class="w50p" :rules="[{ required: true }]">
        <el-input :value="formData.generationTime | formateTime" disabled />
      </el-form-item>
      <el-form-item label="所属工单名称：" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <el-select v-model="formData.taskId" filterable clearable placeholder="请选择所属工单" :disabled="selectedItem !== null" @change="changeTask">
          <el-option v-for="item in getTaskList" :key="item.taskId" :label="item.taskName" :value="item.taskId" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属批次名称：" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <el-input :value="currentBatch.batchName" disabled />
      </el-form-item>
      <el-form-item label="加工批次号：" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <el-input :value="currentBatch.batchNo" disabled />
      </el-form-item>
      <el-form-item label="加工类型：" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <span v-if="currentBatch.batchType">{{ currentBatch.batchType === 'SELF' ? '自主生产' : '委托加工' }}</span>
      </el-form-item>
      <el-form-item v-if="currentBatch.batchType === 'COMMISSION'" label="委托加工商" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <el-select v-model="currentBatch.manufacturingId" style="flex:1;" filterable clearable placeholder="请选择委托加工商" disabled>
          <el-option v-for="item in manufacturingList" :key="item.manufacturingId" :label="item.manufacturingName" :value="item.manufacturingId" />
        </el-select>
      </el-form-item>
      <el-form-item label="加工产品：" class="w50p" :rules="[{ required: true, message: '请选择所属工单' }]">
        <el-input :value="currentBatch.productName" disabled />
      </el-form-item>
      <el-form-item v-if="selectedItem !== null && !!selectedItem.name" label="申请人：" class="w50p">
        <el-input v-model="selectedItem.name" disabled />
      </el-form-item>
      <el-form-item label="备注：" class="w50p">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" :disabled="showType === 'detail'" />
      </el-form-item>
    </el-form>
    <template v-if="currentTask !== null">
      <el-divider v-if="selectedItem === null" content-position="center">
        <span>货品</span>
      </el-divider>
      <div v-if="selectedItem === null && showType !== 'detail'" class="add-btn">
        <el-button @click="addOrder">添加 货品</el-button>
      </div>
      <div v-for="(item, index) in list" :key="item.id" class="list-item">
        <el-divider content-position="left">
          <span>货品 {{ index + 1 }}</span>
        </el-divider>
        <AddItem ref="addItem" :task-detail="currentTask" :selected-item="item" :show-type="showType" :type="type" />
        <div v-if="list.length > 1 && showType !== 'detail'" class="delete-btn">
          <el-button type="danger" @click="delOrder(index)">删除 货品{{ index + 1 }}</el-button>
        </div>
      </div>
    </template>
    <div slot="footer" class="dialog-footer">
      <template v-if="showType !== 'detail'">
        <el-button v-if="selectedItem !== null" :loading="saveLoading2" class="cancelbtn" @click="rebuild()">重新生成</el-button>
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
      </template>
      <template v-else>
        <el-button class="cancelbtn" @click="cancel()">关 闭</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/api/processing-management/process-inventory-manage/index';
import AddItem from './add-item.vue';
import moment from 'moment';
import { getToken } from '@/utils/auth';
export default {
  filters: {
    formateTime: function(value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  components: { AddItem },
  props: {
    value: Boolean,
    showType: {
      type: String,
      default: 'addEdit'
    },
    selectedItem: {
      type: Object,
      default: null
    },
    productList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    taskList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    batchList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    type: {
      type: String,
      default: 'MATERIAL_REQUISITION'
    },
    manufacturingList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      formDataDefault: {
        productionInventoryNo: '',
        taskId: '',
        generationTime: '',
        remark: ''
      },
      formData: {},
      saveLoading: false,
      saveLoading2: false,
      showDialog: false,
      currentBatch: {},
      currentTask: null,
      list: [
        {
          id: this.generateUUID()
        }
      ]
    };
  },
  computed: {
    productionInventoryNoLabel() {
      let label = '';
      const { type } = this;
      if (type === 'MATERIAL_REQUISITION') {
        label = '领料单号：';
      }
      if (type === 'RECEIPT_ORDER') {
        label = '产品入库单号：';
      }
      if (type === 'RETURN_ORDER') {
        label = '原料退库单号：';
      }
      return label;
    },
    titleText() {
      const { showType, type, selectedItem } = this;
      let todo = '详情';
      if (showType === 'addEdit') {
        if (selectedItem !== null) {
          todo = '编辑';
        } else {
          todo = '创建';
        }
      }
      let name = '';
      if (type === 'MATERIAL_REQUISITION') {
        name = `领料单`;
      }
      if (type === 'RECEIPT_ORDER') {
        name = `入库单`;
      }
      if (type === 'RETURN_ORDER') {
        name = `退库单`;
      }
      return `${name}${todo}`;
    },
    getTaskList() {
      const { type, taskList } = this;
      if (type === 'MATERIAL_REQUISITION') {
        return taskList.filter(i => {
          return i.status !== 'CREATE';
        });
      } else {
        return taskList.filter(i => {
          return ['COMPLETED', 'SUSPENDED'].includes(i.status);
        });
      }
    },
    receiptType() {
      const { type } = this;
      if (type === 'MATERIAL_REQUISITION') {
        return 'RAW';
      } else {
        return 'RAW';
      }
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    }
  },
  created() {
    this.reset();
  },
  mounted() {},
  methods: {
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.formDataDefault));
      this.list = [
        {
          id: this.generateUUID()
        }
      ];
      this.currentBatch = {};
      this.currentTask = null;
    },
    async init() {
      const { selectedItem, formData } = this;
      if (selectedItem) {
        for (const key in formData) {
          if (Object.hasOwnProperty.call(formData, key)) {
            formData[key] = selectedItem[key];
          }
        }
        this.changeTask(selectedItem.taskId);
        this.list = selectedItem.goodsList.map(item => {
          return {
            ...item,
            id: this.generateUUID()
          };
        });
      } else {
        this.formData.generationTime = Date.now();
        const no = await this.generateNo();
        this.formData.productionInventoryNo = no;
      }
    },
    async save() {
      const { formData, selectedItem, type, currentBatch } = this;
      const paylod = JSON.parse(JSON.stringify(formData));
      const refs = this.$refs.addItem;
      const list = [];
      for (let i = 0; i < refs.length; i++) {
        const element = refs[i];
        const form = await element.validateForm();
        if (form) {
          list.push(form);
        }
      }
      if (refs.length !== list.length) {
        return false;
      }
      let dateErr = false;
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        const productionDate = moment(element['productionDate'], 'YYYY-MM-DD HH:mm:ss').valueOf();
        const expirationDate = moment(element['expirationDate'], 'YYYY-MM-DD HH:mm:ss').valueOf();
        if (productionDate > expirationDate) {
          dateErr = true;
          break;
        }
      }
      if (dateErr) {
        this.$message.error('开始时间不能大于失效时间');
        return;
      }
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoading = true;
          paylod.generationTime = this.$moment(paylod.generationTime).format('YYYY-MM-DD HH:mm:ss');
          paylod.batchRawMaterialList = this.materialList;
          paylod.type = type;
          paylod.goodsList = list.map(item => {
            return {
              ...item,
              // receiptType,
              OrganizationNo: getToken('organizationNo')
            };
          });
          paylod.batchId = currentBatch.batchId;
          paylod.productId = currentBatch.productId;
          paylod.name = getToken('username');
          paylod.personNo = getToken('personNo');
          if (selectedItem) {
            paylod.productionInventoryId = selectedItem.productionInventoryId;
            api
              .edit(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          } else {
            api
              .add(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    close() {
      setTimeout(() => {
        this.reset();
        this.$refs['form']?.resetFields();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
        this.$refs['form']?.resetFields();
      }, 250);
      this.$emit('input', false);
    },
    changeTask(v) {
      const find = this.taskList.find(item => item.taskId === v);
      if (!find) return;
      this.currentTask = find;
      this.currentBatch = this.batchList.find(item => item.batchId === find.batchId);
      this.list = [
        {
          id: this.generateUUID()
        }
      ];
    },
    async generateNo() {
      const { type } = this;
      const noTypeMap = {
        MATERIAL_REQUISITION: 'MATERIAL_REQUISITION',
        RECEIPT_ORDER: 'RECEIPT_ORDER',
        RETURN_ORDER: 'RETURN_ORDER'
      };
      const notype = noTypeMap[type];
      const res = await api.generateNo(notype);
      if (res.code === 1) {
        return res.data;
      }
      return '';
    },
    addOrder() {
      this.list.push({
        id: this.generateUUID()
      });
    },
    delOrder(index) {
      this.list.splice(index, 1);
    },
    generateUUID() {
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16));
    },
    rebuild() {
      this.init();
      // const { productionInventoryId, taskId } = this.selectedItem;
      // const { type } = this;
      // const paylod = {
      //   productionInventoryId,
      //   taskId,
      //   typeEnum: type
      // };
      // this.saveLoading2 = true;
      // api
      //   .regenerate(paylod)
      //   .then(res => {
      //     if (res.code === 1) {
      //       this.$message.success(res.msg);
      //       this.close();
      //       this.$emit('reflash');
      //     }
      //   })
      //   .finally(_ => {
      //     this.saveLoading2 = false;
      //   });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  min-height: 36px;
  align-items: center;
}
::v-deep .el-form-item__label {
  min-width: 150px !important;
}
::v-deep {
  .el-divider__text {
    background-color: #f0f3f7;
  }
}
.delete-btn {
  text-align: right;
  margin-top: 10px;
}
.add-btn {
  text-align: right;
  margin-bottom: 10px;
}
</style>
